/*
 * @Description: 
 * @Author: duan_shuangjun 丶
 * @Date: 2025-08-20 14:41:05
 * @LastEditTime: 2025-09-21 20:40:54
 */
/*
 * @Description: 
 * @Author: duan_shuangjun 丶
 * @Date: 2025-08-20 14:41:05
 * @LastEditTime: 2025-09-19 17:46:18
 */
import { ipcRenderer, contextBridge } from 'electron'

// --------- Expose some API to the Renderer process ---------
contextBridge.exposeInMainWorld('electronAPI', {
  on(...args: Parameters<typeof ipcRenderer.on>) {
    const [channel, listener] = args
    return ipcRenderer.on(channel, (event, ...args) => listener(event, ...args))
  },
  off(...args: Parameters<typeof ipcRenderer.off>) {
    const [channel, ...omit] = args
    return ipcRenderer.off(channel, ...omit)
  },
  send(...args: Parameters<typeof ipcRenderer.send>) {
    const [channel, ...omit] = args
    return ipcRenderer.send(channel, ...omit)
  },
  invoke(...args: Parameters<typeof ipcRenderer.invoke>) {
    const [channel, ...omit] = args
    return ipcRenderer.invoke(channel, ...omit)
  },

  // You can expose other APTs you need here.
  // ...
})



// 统一域路由门面：api.invoke('auth', 'save', { username, password })
contextBridge.exposeInMainWorld('api', {
  invoke(domain: string, action: string, payload?: any) {
    return ipcRenderer.invoke(`rpc:${domain}`, { action, payload })
  },
})

// 系统相关API
contextBridge.exposeInMainWorld('system', {
  getComputerName: () => ipcRenderer.invoke('system:getComputerName'),
  getPrinters: () => ipcRenderer.invoke('system:getPrinters'),
  getOnlinePrinters: () => ipcRenderer.invoke('system:getOnlinePrinters'),
  printStart: (printerName: string, data: any, pageType: string) =>
    ipcRenderer.invoke('printStart', printerName, data, pageType),

  // WebSocket日志API - 遵循统一门户模式
  writeWsLog: (logLine: string) => ipcRenderer.invoke('write-ws-log', logLine),
  getWsLogs: (options?: { lines?: number, category?: string }) => ipcRenderer.invoke('get-ws-logs', options),
  clearWsLogs: () => ipcRenderer.invoke('clear-ws-logs'),
  getWsLogInfo: () => ipcRenderer.invoke('get-ws-log-info'),

  // 扫码枪功能使用前端键盘监听，无需主进程 API
})

// 简单网络门面
contextBridge.exposeInMainWorld('net', {
  async isOnline() {
    const res = await ipcRenderer.invoke('rpc:net', { action: 'isOnline' })
    return !!res?.data
  },
  async probe() {
    const res = await ipcRenderer.invoke('rpc:net', { action: 'probe' })
    return !!res?.data
  },
  async setOnline(online: boolean) {
    const res = await ipcRenderer.invoke('rpc:net', { action: 'setOnline', payload: { online } })
    return !!res?.data
  }
})

// 同步浏览器 online/offline 到主进程内存态
try {
  const sync = (online: boolean) => ipcRenderer.invoke('rpc:net', { action: 'setOnline', payload: { online } })
  // 初始一次
  if (typeof navigator !== 'undefined') sync(navigator.onLine)
  // 监听变化
  window.addEventListener('online', () => sync(true))
  window.addEventListener('offline', () => sync(false))
} catch { }